//
//  HYFHomeController.m
//  MyOCWeibo
//
//  Created by 黄勇锋 on 16/10/3.
//  Copyright © 2016年 黄勇锋. All rights reserved.
//

#import "HYFHomeController.h"
#import "HYFTitleButton.h"
#import "HYFTemp2Ctrl.h"
#import "HYFPopMenuView.h"
#import "HYFAccount.h"
#import "HYFAccountTool.h"
#import "AFNetworking.h"
#import "AFHTTPSessionManager.h"
#import "HYFUser.h"
#import "MJExtension.h"
#import "HYFStates.h"
#import "HYFLoadMoreView.h"
#import "UIViewController+ESSeparatorInset.h"
#import "HYFUnReadCount.h"
#import <objc/runtime.h>
#import "HYFStatusFrame.h"
#import "HYFStatusCell.h"


@interface HYFHomeController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>

@property (strong,nonatomic) UITableView *dataTableView;

//存放的是 HYFStatusFrame 模型 --> 保留了 HYFStatus 模型
@property (strong,nonatomic) NSMutableArray <HYFStatusFrame *> *statusFrames;

@end


@implementation HYFHomeController


- (UITableView *)dataTableView{
    
    if (_dataTableView == nil) {
        
        _dataTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        
        _dataTableView.delegate = self;
        _dataTableView.dataSource = self;
        
        [_dataTableView registerClass:[HYFStatusCell class] forCellReuseIdentifier:HYFStatusCellID];
    }
    
    return _dataTableView;
}


- (NSMutableArray *)statusFrames{
    if (!_statusFrames) {
        _statusFrames = [NSMutableArray array];
    }
    return _statusFrames;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.dataTableView];
    
    //    UIView *view = [UIView new];
    //    view.height = 0.1;
    //    self.tableView.tableFooterView = view;
    
    //去掉左边的分割线间距
    [self setSeparatorInsetWithTableView:self.dataTableView inset:UIEdgeInsetsZero];
    
    //设置导航栏的内容
    [self setNav];
    //设置刷新控件
    [self setupRefresh];
    //获取个人信息
    [self getUserInfo];
    
//    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(getUnreadCount) userInfo:nil repeats:YES];
    //立即执行,不必等1秒之后再执行
//    [timer fire];
    //加入到运行循环,(默认是加入到   NSRunLoopDefaultModes 里面的,但是当 scrollView 滚动的时候,timer 会停止,而 commonModes 则不会, timerWithTimerInterval: 这个是不会自己加入到 runLoop 里面的.)
//    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)setupRefresh{
    //初始化系统的刷新控件
    UIRefreshControl *control = [[UIRefreshControl alloc] init];
    //添加到tableView上面去
    [self.dataTableView addSubview:control];
    //监听事件
    [control addTarget:self action:@selector(loadNewStatus:) forControlEvents:UIControlEventValueChanged];
    
    [control beginRefreshing];
    [self loadNewStatus:control];
    
    //设置加载更多的控件
    HYFLoadMoreView *loadMore = [HYFLoadMoreView loadMoreView];
    self.dataTableView.tableFooterView = loadMore;
    loadMore.hidden = YES;
}

/**
 *  设置导航栏的内容
 */
- (void)setNav{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" target:self action:@selector(friendsearch)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_pop" target:self action:@selector(pop)];
    
    HYFTitleButton *titleBtn = [[HYFTitleButton alloc] init];
    
    NSString *title = [HYFUserDefaults objectForKey:@"screen_name"];
    if (!title) {
        title = @"我叫首页";
    }
    
    //设置标题与图片
    [titleBtn setTitle:title forState:UIControlStateNormal];
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    titleBtn.backgroundColor = [UIColor redColor];
    
    //设置文字颜色
    [titleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [titleBtn sizeToFit];
    
    //添加点击事件
    [titleBtn addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = titleBtn;
}


- (void)friendsearch{
    NSLog(@"%s",__func__);
    HYFTemp2Ctrl *ctrl = [HYFTemp2Ctrl new];
    [self.navigationController pushViewController:ctrl animated:YES];
    
}

- (void)pop{
    
}

#pragma mark - 请求数据或者点击事件
/**
 *  请求未读信息的个数
 */
- (void)getUnreadCount{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    HYFAccount *account = [HYFAccountTool account];
    
    NSString *urlStr = @"https://rm.api.weibo.com/2/remind/unread_count.json";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    params[@"uid"] = [NSString stringWithFormat:@"%ld", account.uid];
    
    [manager GET:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        //字典转模型
        HYFUnReadCount *unReadCount = [[HYFUnReadCount alloc]init];
        [unReadCount mj_setKeyValues:responseObject];
        
        //给 tabBarItem 赋值,如果有未读,那么显示,否则隐藏
        if (unReadCount.status) {
            
            self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%zd",unReadCount.status];
            //在桌面图标上显示未读条数
            [UIApplication sharedApplication].applicationIconBadgeNumber = unReadCount.status;
        
        }else{
            //在桌面图标上显示未读条数
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            self.tabBarItem.badgeValue = nil;
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
}

/**
 *  请求个人信息
 *
 *  @param uid 用户的Uid
 */
- (void)getUserInfo{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //拼装url与参数
    
    NSString *urlStr = @"https://api.weibo.com/2/users/show.json";
    HYFAccount *account = [HYFAccountTool account];
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    params[@"uid"] = [NSString stringWithFormat:@"%ld", account.uid];
    
    [manager GET:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //MJExtension JSONModle Mantle
        HYFUser *user = [HYFUser new];
        //传入字典给当前模型里面的字段赋值
        [user mj_setKeyValues:responseObject];
        
        NSString *screen_name = user.screen_name;
        //保存昵称
        [HYFUserDefaults setObject:screen_name forKey:@"screen_name"];
        [HYFUserDefaults synchronize];
        
        UIButton *titleButton = (UIButton *)self.navigationItem.titleView;
        [titleButton setTitle:screen_name forState:UIControlStateNormal];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"请求失败:%@",error);
    }];
}


/**
 *  获取新的微博数据
 */
- (void)loadNewStatus:(UIRefreshControl *)control{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //拼装url与参数
    NSString *urlStr = @"https://api.weibo.com/2/statuses/friends_timeline.json";
    HYFAccount *account = [HYFAccountTool account];
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    //    params[@"count"] = @(5);
    
    //since_id-->比传入id的大的微博
    params[@"since_id"] = @(self.statusFrames.firstObject.states.id);
    
    [manager GET:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [control endRefreshing];

        NSArray *dicArray = responseObject[@"statuses"];
        //1.把返回的微博字典数组转成模型数组
        NSArray *statusArray = [HYFStates mj_objectArrayWithKeyValuesArray:dicArray];
        //将 status 模型数组 转换成 statusFrame 模型数组
        NSArray *frameArray = [self convertModelsToFramesWithModels:statusArray];
        //刷新数据,要把新数据添加到数组的前面
        //初始一个添加数组的范围
        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statusArray.count)];
        [self.statusFrames insertObjects:frameArray atIndexes:set];
        
        [self.dataTableView reloadData];
        
        //显示动画
        [self showLoadCountLabelWithCount:statusArray.count];
        
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [control endRefreshing];
        NSLog(@"请求失败:%@",error);
    }];
}

//将请求回来的数据模型数组,转成 frame 模型数组.
- (NSArray *)convertModelsToFramesWithModels:(NSArray *)models{
    
    NSMutableArray *result = [NSMutableArray array];
    
    for (HYFStates *states in models) {
        
        HYFStatusFrame *frame = [[HYFStatusFrame alloc]init];
        
        frame.states = states;
        
        [result addObject:frame];
    }
    return result.copy;
}

- (void)showLoadCountLabelWithCount:(NSInteger)count{
    
    //结束刷新后弹出提示框
    UILabel *label = [[UILabel alloc]init];
    label.size = CGSizeMake(self.view.width, 35);
    label.backgroundColor = [UIColor orangeColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = SYS_FONT(16);
    label.y = CGRectGetMaxY(self.navigationController.navigationBar.frame) - label.height;
    
    //如果刷新出来的数据为 0 的话,显示当前没有新数据,否则显示刷新了 x 条数据.
    NSString *title = 0;
    
    if (count) {
        title = [NSString stringWithFormat:@"刷新出%ld条数据",count];
    }else{
        title = @"当期没有新数据";
    }
    
    label.text = title;
    
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    
    //设置动画
    NSTimeInterval duration = 1.0;
    
    [UIView animateWithDuration:duration animations:^{
        
        //            label.y = CGRectGetMaxY(self.navigationController.navigationBar.frame);
        label.transform = CGAffineTransformMakeTranslation(0, label.height);
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:duration delay:1 options:0 animations:^{
            
            //        label.y = CGRectGetMaxY(self.navigationController.navigationBar.frame) - label.height;
            label.transform = CGAffineTransformIdentity;
            
        } completion:^(BOOL finished) {
            
            [label removeFromSuperview];
        }];
    }];

    
}


- (void)loadMoreStatus{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //拼装url与参数
    
    NSString *urlStr = @"https://api.weibo.com/2/statuses/friends_timeline.json";
    HYFAccount *account = [HYFAccountTool account];
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    //max_id-->比传入id的小于等于的微博
    params[@"max_id"] = @([[self.statusFrames lastObject].states id] - 1);
    [manager GET:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //重置一下加载更多的View的状态
        self.dataTableView.tableFooterView.hidden = YES;
        
        NSArray *dicArray = responseObject[@"statuses"];
        //1.把返回的微博字典数组转成模型数组
        NSArray *statusArray = [HYFStates mj_objectArrayWithKeyValuesArray:dicArray];
        //将 status 模型数组 转换成 statusFrame 模型数组
        NSArray *frameArray = [self convertModelsToFramesWithModels:statusArray];
        //把某个数组里面的子元素添加到另外一个数组里面
        [self.statusFrames addObjectsFromArray:frameArray];
        
        [self.dataTableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        self.dataTableView.tableFooterView.hidden = YES;
        NSLog(@"请求失败:%@",error);
    }];
}
/**
 *  顶部按钮点击
 */
- (void)titleButtonClick:(HYFTitleButton *)button{
    //自定义的view
    UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(5, 12, 100, 100)];
    //设置背景颜色
    customView.backgroundColor = [UIColor redColor];
    //初始化一个pop菜单
    HYFPopMenuView *popMneu = [[HYFPopMenuView alloc] initWithCustomView:customView];
    [popMneu showWithView:button];
}


#pragma mark - Table view data source and delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.statusFrames.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HYFStatusCell *cell = [HYFStatusCell cellWithTableView:tableView];
    //先取出对应行的模型
    HYFStatusFrame *frame = self.statusFrames[indexPath.row];
    //设置值
    cell.statesFrame = frame;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HYFStatusFrame *frame = self.statusFrames[indexPath.row];
    
    return frame.cellHeight;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    [self getUnreadCount];
//    self.tabBarItem.badgeValue = @"15";
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //启动的时候数据为空,不要去加载更多
    if (self.statusFrames.count == 0) {
        return;
    }
    //判断当前如果正在加载的话,就不要去加载更多
    if (self.dataTableView.tableFooterView.hidden == NO) {
        return;
    }
    //tableView.内容高度-tableView.height
    // (20 * 44)880  - 667 = 213 + 底部tabbar的高度
    CGFloat result = scrollView.contentSize.height - scrollView.height + self.tabBarController.tabBar.height - self.dataTableView.tableFooterView.height;
    
    if (result < scrollView.contentOffset.y) {
        self.dataTableView.tableFooterView.hidden = NO;
        [self loadMoreStatus];
    }
}



@end
